package com.hyjoy.util;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * Created by hyjoy on 2018/4/4.
 */
public class DataSourceUtils {
    private static ComboPooledDataSource ds = new ComboPooledDataSource();
    private static ThreadLocal<Connection> tl = new ThreadLocal<>();

    /**
     * 获取数据源
     *
     * @return 连接池
     */
    public static DataSource getDataSource() {
        return ds;
    }

    public static Connection getConnection() throws SQLException {
        Connection connection = tl.get();
        // 若是第一次获取 需要从池中获取一个连接,将这个连接和当前线程绑定
        if (connection == null) {
            connection = ds.getConnection();
            //将这个连接和当前线程绑定
            tl.set(connection);
        }
        return connection;
    }

    /**
     * 开始事务
     *
     * @throws SQLException
     */
    public static void startTransaction() throws SQLException {
        // 获取连接
        Connection connection = getConnection();
        // 开始
        connection.setAutoCommit(false);
    }

    public static void commitAndClose() {
        // 获取连接
        try {
            Connection connection = getConnection();
            connection.commit();
            closeCloseable(connection);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void rollbackAndClose() {
        try {
            // 获取连接
            Connection connection = getConnection();
            // 回滚
            connection.rollback();
            // 关闭并移除
            closeCloseable(connection);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


    /**
     * 释放资源
     *
     * @param connection : 连接
     * @param statement  : 语句执行者
     * @param resultSet  : 结果集
     */
    public static void closeSource(Connection connection, Statement statement, ResultSet resultSet) {
        closeCloseable(connection);
        closeCloseable(statement);
        closeCloseable(resultSet);
    }

    /**
     * 关闭连接
     *
     * @param closeable :
     */
    public static void closeCloseable(AutoCloseable closeable) {
        try {
            closeable.close();
            if (closeable instanceof Connection) {
                tl.remove();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
